package com.longqinuo.mycarservice.fragments;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.longqinuo.mycarservice.R;
import com.longqinuo.mycarservice.adapter.SecondCarAdapter;
import com.longqinuo.mycarservice.entity.SecondCar;
import com.longqinuo.mycarservice.manager.IManager;
import com.longqinuo.mycarservice.manager.MangerImpl;
import com.longqinuo.mycarservice.utils.PathUtils;
import com.longqinuo.mycarservice.view.LruImageCache;


import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.lang.Thread.sleep;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link SecondInfoFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SecondInfoFragment extends Fragment implements View.OnClickListener {

    private PopupWindow popupWindow;
    private FrameLayout mainLayout;
    private ImageView close;
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private ImageView iv_back_car_info;
    private TextView tv_more_config_next;

    private RecyclerView mRecyclerView;
    private SecondCarAdapter mAdapter;
    private List<SecondCar> mList;
    private LinearLayoutManager layoutManager;
    private Map<String,String> map = new HashMap<>();   //post请求参数集合

    private FragmentManager manager;
    private FragmentTransaction mTransaction;
    private LinearLayout ll_collect_car;
    private LinearLayout ll_order_look_car;
    private LinearLayout ll_play_phone_car;
    private static RequestQueue queue;
    private static ImageLoader imageLoader;
    private int mId;
//    private NetworkImageView mBigImage;

    private ViewPager mBanner;      //轮播图
    private List<NetworkImageView> mImageList;
    private PagerAdapter mPagerAdapter;
    private boolean flag = true;
    private MyAsyncTask myAsyncTask;  //自定义的异步任务

    private TextView mTitle;
    private TextView mName;
    private TextView mPrice;
    private TextView mMileage;
    private TextView mFirst;
    private TextView mTap;
    private TextView mColor;
    private TextView mTimes;
    private TextView mAddress;
    private TextView storeName;
    private TextView storeAddress;
    private TextView storeDesc;
    private SecondCar s = new SecondCar();  //二手车对象 用于存入数据库
    private IManager iManager;   //数据库代理管理器
    private boolean isCollect;
    private ImageView collectStar;  //收藏星星
    private TextView collectText;  //收藏文字
    public SecondInfoFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SecondInfoFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SecondInfoFragment newInstance(String param1, String param2) {
        SecondInfoFragment fragment = new SecondInfoFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mId = Integer.valueOf(mParam1);
            s.setId(mId); //为对象设置ID
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        init();
    }

    private void init() {  //初始化操作
        queue = Volley.newRequestQueue(getActivity());
        LruImageCache lruImageCache = LruImageCache.instance();
        imageLoader = new ImageLoader(queue, lruImageCache);

        manager = getActivity().getSupportFragmentManager();
        iManager = new MangerImpl(getActivity(),new SecondCar());  //实例化数据库代理管理器
        isCollect = iManager.isExists(mId);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_second_info, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        mainLayout = (FrameLayout) view.findViewById(R.id.fl_car_info_layout);
        iv_back_car_info = (ImageView) view.findViewById(R.id.iv_back_car_info);
        iv_back_car_info.setOnClickListener(this);
        tv_more_config_next = (TextView) view.findViewById(R.id.tv_more_config_next);
        tv_more_config_next.setOnClickListener(this);

        mRecyclerView = (RecyclerView) view.findViewById(R.id.rv_car_info_list);

        ll_collect_car = (LinearLayout) view.findViewById(R.id.ll_collect_car);
        ll_collect_car.setOnClickListener(this);
        ll_order_look_car = (LinearLayout) view.findViewById(R.id.ll_order_look_car);
        ll_order_look_car.setOnClickListener(this);
        ll_play_phone_car = (LinearLayout) view.findViewById(R.id.ll_play_phone_car);
        ll_play_phone_car.setOnClickListener(this);

        mBanner = (ViewPager) view.findViewById(R.id.id_banner_car);
//        mBigImage = (NetworkImageView) view.findViewById(R.id.niv_image_car_info);
        mTitle = (TextView) view.findViewById(R.id.tv_title_top_info);
        mName = (TextView) view.findViewById(R.id.tv_name_car_info);
        mPrice = (TextView) view.findViewById(R.id.tv_price_car_info);
        mMileage = (TextView) view.findViewById(R.id.tv_mileage_car_info);
        mFirst = (TextView) view.findViewById(R.id.tv_first_car_infor);
        mTap = (TextView) view.findViewById(R.id.tv_tap_car_info);
        mColor = (TextView) view.findViewById(R.id.tv_color_car_info);
        mTimes = (TextView) view.findViewById(R.id.tv_times_car_info);
        mAddress = (TextView) view.findViewById(R.id.tv_address_car_info);
        storeName = (TextView) view.findViewById(R.id.tv_store_name);
        storeAddress = (TextView) view.findViewById(R.id.tv_store_address);
        storeDesc = (TextView) view.findViewById(R.id.tv_store_desc);
        collectStar = (ImageView) view.findViewById(R.id.iv_collect_star_car);
        collectText = (TextView) view.findViewById(R.id.tv_collect_text_car);
        initData();
    }

    private void initData() {
        if (isCollect) {
            collectText.setText("已收藏");
        } else {
            collectText.setText("收藏");
        }
        collectStar.setSelected(isCollect);
        collectText.setSelected(isCollect);


        mList = new ArrayList<>();

        mAdapter = new SecondCarAdapter(mList, R.layout.second_car_item_layout, imageLoader);
        layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mAdapter.setOnItemClickListener(new SecondCarAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View itemView, int position) {
                mTransaction = manager.beginTransaction();
                mTransaction.add(R.id.ll_main_layout, SecondInfoFragment.newInstance(mList.get(position).getId() + "", ""), "SecondInfo");
                mTransaction.addToBackStack("SecondInfo");
                mTransaction.commit();
            }
        });
        mRecyclerView.setAdapter(mAdapter);
        requestData();  //请求 车辆数据

    }


    @Override
    public void onPause() {   //失去焦点时将当前任务标记为取消  防止阻塞下一个轮播
        super.onPause();
        if (myAsyncTask != null && myAsyncTask.getStatus() == AsyncTask.Status.RUNNING) {
            // cancel 方法只是将对应的AsyncTask 标记为取消状态  并不是取消线程的执行
            myAsyncTask.cancel(true);
        }
    }

    private void requestCar() {  //请求查找车辆
        mList.clear();
        StringRequest request = new StringRequest(Request.Method.POST, PathUtils.QUERY_CAR, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Gson gson=new Gson();
                String jsonData = null;
                try {

                    JSONObject jsonObject = new JSONObject(s);
                    int code = jsonObject.getInt("code");
                    if (code==0) {
                        jsonData = jsonObject.getString("data");
                        List<SecondCar> carList = gson.fromJson(jsonData, new TypeToken<List<SecondCar>>(){}.getType());
                        mList.addAll(carList);
                        mAdapter.notifyDataSetChanged();

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.e(">>>>>","查找车辆"+volleyError.toString());
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                return map;
            }
        };
        queue.add(request);

    }

    private void requestData() {  //请求车辆详细数据
        JsonObjectRequest request = new JsonObjectRequest(PathUtils.CAR_CONFIG+"?id="+mId, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                try {
                    int code = jsonObject.getInt("code");
                    if (code==0) {
                        JSONObject o = jsonObject.getJSONObject("data");
                        String title = o.getString("title");
                        mTitle.setText(title);
                        mName.setText(title);
                        s.setTitle(title); //为对象设置Title

                        double price = o.getDouble("price");
                        mPrice.setText("￥"+price);
                        s.setPrice(price); //为对象设置Price

                        double mileage = o.getDouble("km");
                        mMileage.setText(mileage+"万公里");
                        s.setKm(mileage); //为对象设置Km

                        String buyDate = o.getString("buyDate");
                        mFirst.setText(buyDate);
                        s.setBuyDate(buyDate); //为对象设置buyDate

                        String auto = o.getString("auto");
                        double outputValue = o.getDouble("outputValue");
                        mTap.setText(auto+"/"+outputValue+"L");

                        String color = o.getString("color");
                        mColor.setText(color);

                        int transferTime = o.getInt("transferTime");
                        mTimes.setText(transferTime+"次");

                        String district = o.getString("district");
                        mAddress.setText(district);

                        String company = o.getString("company");
                        storeName.setText(company);

                        String place = o.getString("place");
                        storeAddress.setText(place);

                        String detail = o.getString("detail");
                        storeDesc.setText(detail);

                        String image = o.getString("image");
                        String imgs[] = image.split(",");
//                        mBigImage.setImageUrl(PathUtils.CAR_PHOTO+imgs[0],imageLoader);
                        initImage(imgs);
                        s.setImage(image);  //为对象设置Image

                        String tab = o.getString("tab");
                        s.setTab(tab);  //为对象设置Tab

                        String type = o.getString("type");
                        if (map.containsKey("type")) {
                            map.remove("type");
                        }
                        map.put("type",type);  //选择品牌
                        requestCar();  //查询车辆
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
        queue.add(request);
    }
    private void initImage(String images[]) {   //初始化轮播图数据
        mImageList = new ArrayList<>();
        for (int i = 0; i < images.length; i++) {
            NetworkImageView imageView = new NetworkImageView(getActivity());
            imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setImageUrl(PathUtils.CAR_PHOTO+images[i],imageLoader);
            mImageList.add(imageView);
            imageView = null;
        }
        mPagerAdapter = new PagerAdapter() {
            @Override
            public int getCount() {
                return Integer.MAX_VALUE;
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view==object;
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                position = position%(mImageList.size());
                container.addView(mImageList.get(position));
                return mImageList.get(position);
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                position = position%(mImageList.size());
                container.removeView(mImageList.get(position));
            }
        };
        mBanner.setAdapter(mPagerAdapter);
        int currentPositio = mBanner.getCurrentItem();
        mBanner.setCurrentItem(currentPositio);

        mBanner.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                position = position%(mImageList.size());
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        myAsyncTask = new MyAsyncTask(); //只能在UI 线程中创建轮播任务
        myAsyncTask.execute();         //只能执行一次  多次执行会出现异常

    }
    private class MyAsyncTask extends AsyncTask<Void,Void,Void> {
        @Override
        protected Void doInBackground(Void... params) {
            while (flag) {
                try {
                    sleep(2000);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                publishProgress();
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
            if (isCancelled()) {  //判断该任务是否引进取消
                return;
            }
            int mPositon = mBanner.getCurrentItem();

            mBanner.setCurrentItem(++mPositon);
        }
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }


    @Override
    public void onClick(View v) {
        mTransaction = manager.beginTransaction();
        switch (v.getId()) {
            case R.id.iv_back_car_info:
                manager.popBackStack();
                break;
            case R.id.tv_more_config_next:
                mTransaction.add(R.id.ll_main_layout, MoreConfigFragment.newInstance(mId+"",""), "MoreConfig");
                mTransaction.addToBackStack("MoreConfig");
                mTransaction.commit();
                break;
            case R.id.ll_collect_car:    //收藏二手车 或取消
                if (isCollect) {
                    int delete = iManager.delete(s);
                    if (delete!=0) {
                        collectText.setText("收藏");
                        Toast.makeText(getActivity(), "取消收藏", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    long add = iManager.add(s);
                    if (add!=0) {
                        collectText.setText("已收藏");
                        Toast.makeText(getActivity(), "收藏成功", Toast.LENGTH_SHORT).show();
                    }
                }
                isCollect = !isCollect;
                collectStar.setSelected(isCollect);
                collectText.setSelected(isCollect);

                break;
            case R.id.ll_order_look_car:
                getPopupWindow();
                break;
            case R.id.ll_play_phone_car:
                break;
            case R.id.iv_close_order_success:
                popupWindow.dismiss();
                mTransaction.add(R.id.ll_main_layout, new OrderCarFragment(), "OrderCar");
                mTransaction.addToBackStack("OrderCar");
                mTransaction.commit();
                break;
        }
    }

    public void getPopupWindow() {
        View view = View.inflate(getActivity(), R.layout.order_car_success_pop, null);
        close = (ImageView) view.findViewById(R.id.iv_close_order_success);
        close.setOnClickListener(this);
        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        setAlpha(0.8f);
        popupWindow.setTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAtLocation(mainLayout, Gravity.CENTER, 0, 0);
        popupWindow.update();
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setAlpha(1.0f);
            }
        });
    }

    private void setAlpha(float alpha) {  //设置popupWindow之外的透明度
        Window w = getActivity().getWindow();
        WindowManager.LayoutParams lp = w.getAttributes();
        lp.alpha = alpha;
        w.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        w.setAttributes(lp);
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
